#!/bin/bash

# 群辉证书生成工具增强版
# 功能：支持自签RSA/ECC证书，生成Let's Encrypt兼容的ECC证书

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

clear

echo -e "${GREEN}=== 群辉证书生成工具增强版 ===${NC}"
echo -e "${BLUE}支持：1. 自签RSA证书  2. 自签ECC证书  3. Let's Encrypt兼容ECC证书${NC}"
echo ""

# 选择证书类型
echo -e "${YELLOW}请选择证书类型：${NC}"
echo "1) 自签RSA证书（兼容旧设备）"
echo "2) 自签ECC证书（更安全高效）"
echo "3) Let's Encrypt兼容ECC证书（P-256，推荐群辉使用）"
read -p "请输入选择（1-3，默认1）: " CERT_TYPE
CERT_TYPE=${CERT_TYPE:-1}

# 用户输入
read -p "请输入域名（默认: localhost）: " DOMAIN
DOMAIN=${DOMAIN:-localhost}

case $CERT_TYPE in
    1)
        # RSA配置
        read -p "请输入RSA密钥长度（bit，默认: 2048）: " KEY_SIZE
        KEY_SIZE=${KEY_SIZE:-2048}
        ALGO="rsa:${KEY_SIZE}"
        KEY_FILE_EXT="key"
        ;;
    2|3)
        # ECC配置（包括Let's Encrypt兼容）
        echo -e "${BLUE}将使用ECC P-256曲线（secp256r1）${NC}"
        ALGO="ec"
        EC_PARAMS="-name prime256v1"
        KEY_FILE_EXT="ec.key"
        
        if [ $CERT_TYPE -eq 3 ]; then
            echo -e "${GREEN}生成Let's Encrypt兼容的ECC证书...${NC}"
            DAYS=90  # Let's Encrypt默认有效期
        else
            read -p "请输入证书有效期（天，默认: 365）: " DAYS
            DAYS=${DAYS:-365}
        fi
        ;;
    *)
        echo -e "${RED}无效选择！${NC}"
        exit 1
        ;;
esac

if [ $CERT_TYPE -ne 3 ]; then
    read -p "请输入证书有效期（天，默认: 365）: " DAYS
    DAYS=${DAYS:-365}
fi

# 固定输出目录
OUTPUT_DIR="./certs"
mkdir -p "$OUTPUT_DIR"

# 文件路径
KEY_FILE="${OUTPUT_DIR}/${DOMAIN}.${KEY_FILE_EXT}"
CRT_FILE="${OUTPUT_DIR}/${DOMAIN}.crt"
PFX_FILE="${OUTPUT_DIR}/${DOMAIN}.pfx"
CONFIG_FILE="${OUTPUT_DIR}/openssl.cnf"

# 生成OpenSSL配置（修正版）
cat > "$CONFIG_FILE" <<EOL
[req]
distinguished_name = req_distinguished_name
req_extensions = req_ext
prompt = no

[req_distinguished_name]
CN = ${DOMAIN}

[req_ext]
subjectAltName = DNS:${DOMAIN}

[v3_ext]
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth, clientAuth
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
subjectAltName = DNS:${DOMAIN}
EOL

echo -e "\n${YELLOW}即将生成以下证书：${NC}"
echo "域名:      ${DOMAIN}"
echo "类型:      $([ $CERT_TYPE -eq 1 ] && echo "RSA ${KEY_SIZE}-bit" || echo "ECC P-256")"
echo "有效期:    ${DAYS} 天"
echo "输出目录:  $(realpath "$OUTPUT_DIR")"

read -p "是否继续？(y/n) " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${RED}操作已取消${NC}"
    rm -f "$CONFIG_FILE"
    exit 1
fi

# 生成私钥
echo -e "\n1. 生成私钥: ${KEY_FILE}"
if [ $CERT_TYPE -eq 1 ]; then
    openssl genrsa -out "${KEY_FILE}" ${KEY_SIZE}
else
    openssl ecparam -genkey ${EC_PARAMS} -out "${KEY_FILE}"
fi

# 生成自签证书（修正版）
echo -e "\n2. 生成证书: ${CRT_FILE}"
if [ $CERT_TYPE -eq 3 ]; then
    # Let's Encrypt风格证书（使用修正的扩展配置）
    openssl req -new -sha256 -key "${KEY_FILE}" \
        -out "${OUTPUT_DIR}/csr.csr" -config "$CONFIG_FILE" \
        -extensions req_ext
    
    openssl x509 -req -sha256 -days ${DAYS} \
        -in "${OUTPUT_DIR}/csr.csr" -signkey "${KEY_FILE}" \
        -out "${CRT_FILE}" -extfile "$CONFIG_FILE" -extensions v3_ext
    rm -f "${OUTPUT_DIR}/csr.csr"
else
    # 普通自签证书
    openssl req -x509 -new -nodes -key "${KEY_FILE}" \
        -sha256 -days ${DAYS} -out "${CRT_FILE}" \
        -config "$CONFIG_FILE" -extensions req_ext
fi

# 生成PKCS12文件
echo -e "\n3. 生成PKCS12文件: ${PFX_FILE}"
openssl pkcs12 -export -out "${PFX_FILE}" \
    -inkey "${KEY_FILE}" -in "${CRT_FILE}" \
    -passout pass: -certfile "${CRT_FILE}"

# 设置权限
chmod 600 "${KEY_FILE}" "${PFX_FILE}"
chmod 644 "${CRT_FILE}"
rm -f "$CONFIG_FILE"

# 验证生成结果
echo -e "\n${GREEN}=== 证书生成成功 ===${NC}"
echo -e "${YELLOW}证书信息：${NC}"
openssl x509 -in "${CRT_FILE}" -text -noout | grep -E "Subject:|Not Before|Not After|DNS:|Public Key Algorithm:"

echo -e "\n${YELLOW}密钥信息：${NC}"
if [ $CERT_TYPE -eq 1 ]; then
    openssl rsa -in "${KEY_FILE}" -text -noout | head -n 1
else
    openssl ec -in "${KEY_FILE}" -text -noout | head -n 5
fi

echo -e "\n${YELLOW}生成的文件：${NC}"
ls -lh "${KEY_FILE}" "${CRT_FILE}" "${PFX_FILE}"

# 群辉专用说明
echo -e "\n${RED}群辉使用说明：${NC}"
echo "1. 将 ${CRT_FILE} 和 ${KEY_FILE} 导入到："
echo "   控制面板 > 安全性 > 证书"
echo "2. Let's Encrypt ECC证书注意事项："
echo "   - 群辉内置的自动续签默认使用相同算法"
echo "   - 如需自动续签，请确保证书安装在默认位置"
echo "   - 推荐使用ACME客户端自动获取证书"